package com.framework;

import java.util.EnumSet;

// 缓存装饰器
class CacheDecorator<T, R> extends ComponentDecorator<T, R> {
    private final CacheManager cacheManager;
    private final int ttlSeconds;

    public CacheDecorator(Component<T, R> delegate, CacheManager cacheManager, int ttlSeconds,
                          EnumSet<ComponentFeature> features) {
        super(delegate, features);
        this.cacheManager = cacheManager;
        this.ttlSeconds = ttlSeconds;
        features.add(ComponentFeature.CACHING);
    }

    @Override
    public String getType() {
        return delegate.getType() + "#CACHE";
    }

    @Override
    public ComponentOutput<R> execute(ComponentContext<T> context) {
        String cacheKey = generateCacheKey(context);
        ComponentOutput<R> cached = cacheManager.get(cacheKey);
        if (cached != null) {
            return cached;
        }

        ComponentOutput<R> result = delegate.execute(context);
        cacheManager.put(cacheKey, result, ttlSeconds);
        return result;
    }

    private String generateCacheKey(ComponentContext<T> context) {
        return delegate.getType() + ":" + context.hashCode();
    }
}
